<template>
  <div class="callAnalysisNew-TabEntirety">
    <el-table-form ref="form" :model="query">
      <el-form-item label="统计日期" prop="date" :table-form-merge="2">
        <el-date-picker
          v-model="query.date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
          :picker-options="pickerOptions"
        />
      </el-form-item>

      <!-- <el-form-item label="设备" prop="num">
        <el-select v-model="query.num" clearable>
          <el-option
            v-for="item in numOptions"
            :key="item.keyVal"
            :label="item.keyName"
            :value="item.keyVal"
          />
        </el-select>
      </el-form-item> -->

      <template v-slot:btns>
        <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      border
      element-loading-text="加载中"
      :column="column"
      :data="tableData"
      custom-column
      :height="180"
      :span-method="arraySpanMethod"
      :header-cell-style="headerStyle"
    />
    <div class="chart-body">
      <Charts :options="option" />
    </div>
  </div>
</template>

<script>
  import Charts from '@/components/Charts'
  import { callAnalysisNewEntiretyTable, callAnalysisNewEntiretyChart } from '@/api'
  import dayjs from 'dayjs'
  export default {
    components: {
      Charts
    },
    data() {
      return {
        query: {
          date: [new Date(), new Date()],
          num: ''
        },
        numOptions: [],
        tableData: [],
        option: {}
      }
    },
    computed: {
      pickerOptions() {
        return {
          shortcuts: [
            {
              text: '今天',
              onClick(picker) {
                const end = new Date()
                const start = new Date()
                picker.$emit('pick', [start, end])
              }
            },
            {
              text: '最近7天',
              onClick(picker) {
                const end = new Date()
                let start = new Date()
                start = dayjs().subtract(7, 'day').toDate()
                picker.$emit('pick', [start, end])
              }
            },
            {
              text: '最近30天',
              onClick(picker) {
                const end = new Date()
                let start = new Date()
                start = dayjs().subtract(30, 'day').toDate()
                picker.$emit('pick', [start, end])
              }
            }
          ]
        }
      },
      column() {
        return [
          {
            prop: 'itemName',
            label: '项目',
            width: 120
          // renderHeader: (h, scope) => {
          //   return <span><i class="el-icon-time"></i>{ scope.column.label }</span>
          // }
          },
          {
            prop: 'statistics1',
            label: '呼入电话统计',
            children: [
              {
                label: '呼入电话',
                prop: 'totalCallIn',
                align: 'center',
                width: 120,
                render: (h, { row, $index }) => (
                <span class={$index === 2 ? 'red' : ''}>{row.totalCallIn}</span>
              )
              },
              {
                label: '用户取消',
                prop: 'userAbandon',
                align: 'center',
                width: 120
              },
              {
                label: '值班电话',
                prop: 'toDivert',
                align: 'center',
                width: 120
              },
              {
                label: '坐席电话',
                prop: 'toStation',
                align: 'center',
                width: 120
              }
            ]
          },
          {
            prop: 'statistics2',
            label: '坐席电话统计',
            children: [
              {
                label: '未进入队列',
                prop: 'toStationNoqueue',
                align: 'center',
                width: 120
              },
              {
                label: '进入队列',
                prop: 'toStationQueue',
                align: 'center',
                width: 120
              },
              {
                label: '直通率',
                prop: 'abandonNoservice',
                align: 'center',
                width: 120,

                render: (h, { row, $index }) => (
                <span class={$index === 0 ? 'red' : ''}>{row.abandonNoservice}</span>
              )
              },
              {
                label: '直通率',
                prop: 'toBlackList',
                align: 'center',
                width: 120
              }
            ]
          },
          {
            prop: 'statistics3',
            label: '时长统计(s)',
            children: [
              {
                label: '平均通话',
                prop: 'averageTalktime',
                align: 'center',
                width: 120
              },
              {
                label: '应答电话平均等待',
                prop: 'averageWaittimeOfTalk',
                align: 'center',
                minWidth: 180
              }
            ]
          }
        ]
      }
    },
    mounted() {
      this.search()
    },
    methods: {
      search() {
        const params = {
          num: this.query.num || 1
        }
        if (this.query.date && this.query.date.length > 0) {
          params[`startDt`] = this.query.date[0].toString()
          params[`endDt`] = this.query.date[1].toString()
        }
        this.getTableData(params)
        this.getChartData(params)
      },
      async getTableData(params) {
        const { status, data } = await callAnalysisNewEntiretyTable(params)
        if (status === 200) {
          if (data.length) {
            let passRate =
              ((data[0].toStationNoqueue / data[0].toStation) * 100).toFixed(2) + '%'

            let answerRate =
              ((data[1].toStation / data[0].toStation) * 100).toFixed(2) + '%'
            if (data[0].toStation === 0) {
              passRate = 0
              answerRate = 0
            }
            data[0].abandonNoservice = passRate
            data[1].userAbandon = ''
            data[2].totalCallIn = answerRate
          }
          this.tableData = data
        }
      },
      async getChartData(params) {
        const { status, data } = await callAnalysisNewEntiretyChart(params)
        if (status === 200) {
          console.log(data)
          // this.tableData = data

          const type = this.query.date[1] - this.query.date[0] === 0 ? 1 : 2

          this.chartInit(data, type)
        }
      },
      chartInit(data, type) {
        // type 1 每小时统计数据  type 2 每日统计数据
        let xAxis = []
        const totalCallIn = []
        const answerRate = []
        const passRate = []

        // 处理数据
        data.totalCallAndRate.forEach((v, index) => {
          if (type === 1) {
            xAxis = [
              '0-1点',
              '1-2点',
              '2-3点',
              '3-4点',
              '4-5点',
              '5-6点',
              '6-7点',
              '7-8点',
              '8-9点',
              '9-10点',
              '10-11点',
              '11-12点',
              '12-13点',
              '13-14点',
              '14-15点',
              '15-16点',
              '16-17点',
              '17-18点',
              '18-19点',
              '19-20点',
              '20-21点',
              '21-22点',
              '22-23点',
              '23-00点'
            ]

            if (index === 0) {
              totalCallIn.push(v.totalCallIn)
              if (v.toStation !== 0) {
                answerRate.push(v.toStationTalk / v.toStation)
              } else {
                answerRate.push(0)
              }

              if (v.toStationNoqueue > 0) {
                passRate.push(v.toStationNoqueue / v.toStation)
              } else {
                passRate.push(0)
              }
            } else {
              const preItem = data.totalCallAndRate[index - 1]
              if (v.totalCallIn > 0) {
                totalCallIn.push(v.totalCallIn - preItem.totalCallIn)
              } else {
                totalCallIn.push(0)
              }

              if (v.toStation - preItem.toStation > 0) {
                answerRate.push(
                  (v.toStationTalk - preItem.toStationTalk) /
                    (v.toStation - preItem.toStation)
                )
              } else {
                answerRate.push(0)
              }

              if (v.toStation - preItem.toStation > 0) {
                passRate.push(
                  (v.toStationNoqueue - preItem.toStationNoqueue) /
                    (v.toStation - preItem.toStation)
                )
              } else {
                passRate.push(0)
              }
            }
          } else {
            xAxis.push(v.happendHour)
            totalCallIn.push(v.totalCallIn)

            if (v.toStation !== 0) {
              answerRate.push(v.toStationTalk / v.toStation)
            } else {
              answerRate.push(0)
            }

            if (v.toStationNoqueue > 0) {
              passRate.push(v.toStationNoqueue / v.toStation)
            } else {
              passRate.push(0)
            }
          }
        })

        this.option = {
          title: {
            y: 20,
            text: type === 1 ? '每小时数据统计图' : '每日数据统计图'
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            hideDelay: 50,
            padding: 10,
            textStyle: {
              color: 'white',
              decoration: 'none',
              fontFamily: 'Verdana, sans-serif',
              fontSize: 15,
              fontStyle: 'italic'
            // fontWeight: 'bold'
            },
            formatter: function(params, ticket, callback) {
              var res = params[0].name
              for (var i = 0; i < params.length; i++) {
                if (i === 0) {
                  res += '<br/>' + params[i].seriesName + ':' + params[i].value
                } else {
                  res +=
                    '<br/>' +
                    params[i].seriesName +
                    ':' +
                    (params[i].value * 100).toFixed(2) +
                    '%'
                }
              }
              setTimeout(function() {
                // 仅为了模拟异步回调
                callback(ticket, res)
              }, 0)
              return '正在加载中...'
            }
          },
          legend: {
            y: 20,
            data: ['呼入电话总数', '应答率', '直通率']
          },
          toolbox: {
            show: false,
            feature: {
              mark: {
                show: false
              },
              dataView: {
                show: true,
                readOnly: false
              },
              magicType: {
                show: true,
                type: ['line', 'bar']
              },
              restore: {
                show: true
              },
              saveAsImage: {
                show: true
              }
            }
          },
          grid: {
            y: '20%',
            top: 80
          },
          xAxis: {
            splitLine: {
              show: false
            }, // 去除网格线
            data: xAxis
          },
          yAxis: [
            {
              splitLine: {
                show: false
              }, // 去除网格线
              type: 'value',
              name: '呼入数量',
              nameTextStyle: {
                color: '#666666'
              },
              min: 0
            },
            {
              splitLine: {
                show: false
              }, // 去除网格线
              type: 'value',
              name: '百分比',
              nameTextStyle: {
                color: '#666666'
              },
              max: 1,
              min: 0,
              axisLabel: {
                formatter: function(value) {
                  return value * 100 + '%'
                }
              }
            }
          ],
          calculable: false,
          series: [
            {
              type: 'bar',
              barWidth: 30,
              name: '呼入电话总数',
              itemStyle: {
                normal: {
                  color: '#36a9ce',
                  label: {
                    show: true,
                    textStyle: {
                      fontSize: 12
                    }
                  }
                }
              },
              data: totalCallIn,
              markPoint: {
                data: [
                  {
                    type: 'max',
                    name: '最大值'
                  },
                  {
                    type: 'min',
                    name: '最小值'
                  }
                ]
              }
            },
            {
              type: 'line',
              name: '应答率',
              yAxisIndex: 1,
              symbol: 'circle',
              itemStyle: {
                normal: {
                  color: '#ff1700',
                  //                                borderColor:'black',
                  //                                borderWidth:0.1,
                  label: {
                    show: true,
                    textStyle: {
                      color: '#ff1700',
                      fontSize: 12
                    },
                    formatter: function(value) {
                      return (value.value * 100).toFixed(2) + '%'
                    }
                  },
                  lineStyle: {
                    width: 1.5
                  //                                    color:'#ff9999'
                  }
                }
              },
              data: answerRate
            },
            {
              type: 'line',
              name: '直通率',
              yAxisIndex: 1,
              symbol: 'circle',
              itemStyle: {
                normal: {
                  color: '#005570',
                  //                                borderColor:'black',
                  //                                borderWidth:0.1,
                  label: {
                    show: true,
                    textStyle: {
                      color: '#005570',
                      fontSize: 12
                    },
                    formatter: function(value) {
                      return (value.value * 100).toFixed(2) + '%'
                    }
                  },
                  lineStyle: {
                    width: 1.5
                  //                                    color:'#ffcc99'
                  }
                }
              },
              data: passRate
            }
          ]
        }
      },
      // 表格合并
      arraySpanMethod({ row, column, rowIndex, columnIndex }) {
        if (rowIndex === 0) {
          if (column.property === 'abandonNoservice') {
            return [1, 2]
          }
          if (column.property === 'toBlackList') {
            return [0, 0]
          }
        }

        if (rowIndex === 2) {
          if (columnIndex <= 5 && columnIndex > 2) {
            return [1, 0]
          }
          if (columnIndex === 1) {
            return [1, 4]
          }
        }
      },
      // 表头合并
      headerStyle({ row, column, rowIndex, columnIndex }) {
        if (row.length === 10) {
          row[6].colSpan = 2
          row[7].colSpan = 0
        }
        if (columnIndex === 7) {
          return 'display: none'
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
.callAnalysisNew-TabEntirety {
  .chart-body {
    height: 400px;
  }

  /deep/.red {
    color: #c00;
  }
}
</style>
